package system;

import Main.Parameters;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Exit Timer.
 * 1-st timer alarms after  QuitTime and if !stop sets Exit=true
 * 2-nd Every second checks if stop is true if it's true it cancels both timers. If 1st timer is off the 2nd turns off too.
 * @author zem
 */
public class ExitTimer implements Runnable {

    public static boolean stop;

    

    public void run() {
        stop=false;
        Parameters.ExitTimerIsWorking=true;
       TimerRun(Parameters.QuitTime);
       
       SecondTimerRun();

    }
 Timer timer;
 Timer everysecondtimer;
   

     public void TimerRun ( int seconds )   {
         timer = new Timer (  ) ;
         timer.schedule ( new Alarm (  ) , seconds*1000 ) ;
      }


     class Alarm extends TimerTask  {
         public void run (  )   {
             if(!stop){ Parameters.exit = true;
             stop=false;
           notifyAll();
                        }
             Parameters.ExitTimerIsWorking=false;
       timer.cancel (  ) ; //Terminate the timer thread
          }
      }

      public void SecondTimerRun ( )   {
         everysecondtimer = new Timer (  ) ;
       
         
         everysecondtimer.schedule ( new Check (  ) , 500, 500) ;
      }
       class Check extends TimerTask  {
         public void run (  )   {
             
            if(stop) {
                System.out.println(new Message("ev0003").message);
        Parameters.ExitTimerIsWorking = false;
                timer.cancel(); //if stop parameter is true
            everysecondtimer.cancel();
            }
            if (!Parameters.ExitTimerIsWorking)  {  everysecondtimer.cancel();}
         }
       }
}
